using System;
using System.IO;

using octalforty.Componento.SemanticModel;

namespace octalforty.Componento.ComponentModel.Packaging
{
    public class LocalFileSystemPackageRepositoryBrowser : IRepositoryBrowser
    {
        private readonly Core.IServiceProvider serviceProvider;

        public LocalFileSystemPackageRepositoryBrowser(Core.IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }

        public RepositoryEntry[] GetPackageReferences()
        {
            string packageDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "Packages.cpr");
            PackageRepositoryDefinitionParser packageRepositoryDefinitionParser = new PackageRepositoryDefinitionParser();

            RepositoryEntry[] repositoryEntries;
            using(StreamReader streamReader = new StreamReader(packageDirectoryPath, true))
                repositoryEntries = packageRepositoryDefinitionParser.ParseRepositoryDefinition(streamReader);

            return repositoryEntries;
        }

        public bool CanOpenRepository(Uri repositoryUri)
        {
            return repositoryUri.Scheme.ToLowerInvariant() == "file";
        }

        public Repository OpenRepository(Uri repositoryUri)
        {
            string packageDirectoryPath = Path.Combine(repositoryUri.LocalPath, "Packages.cpr");
            PackageRepositoryDefinitionParser packageRepositoryDefinitionParser = new PackageRepositoryDefinitionParser();

            RepositoryEntry[] repositoryEntries;
            using(StreamReader streamReader = new StreamReader(packageDirectoryPath, true))
                repositoryEntries = packageRepositoryDefinitionParser.ParseRepositoryDefinition(streamReader);

            return new Repository(repositoryUri, repositoryEntries);

            return null;
            /*string packageDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "Packages.cpd");
            PackageRepositoryDefinitionParser packageRepositoryDefinitionParser = new PackageRepositoryDefinitionParser();

            RepositoryEntry[] repositoryEntries;
            using (StreamReader streamReader = new StreamReader(packageDirectoryPath, true))
                repositoryEntries = packageRepositoryDefinitionParser.ParseRepositoryDefinition(streamReader);

            return repositoryEntries;*/
        }
    }
}
